<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Cache;

/**
 * 省份
 * Class Province
 *
 * @package App\Models
 * @property int $id
 * @property string $name 名称
 * @property string $code 代码
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Province whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Province whereCode($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Province whereName($value)
 * @mixin \Eloquent
 */
class District extends Model
{
    const CACHE_TAG = 'district';

    public $timestamps = false;

    protected $table = 'xyj_district';

    protected $fillable = [];

    public function getList($id)
    {
        $infos = self::where('upid', '=', $id)->select(['id', 'name'])->get()->pluck('name', 'id');
        foreach ($infos as $info) {
            $list[$info->id] = $info->name;
        }
        return $list;

    }

    /**
     * 用于select的省份列表
     * @return array
     */
    public static function getProvinceList()
    {
        $result = \Cache::tags(self::CACHE_TAG)->rememberForever('new-province-list:', function () {
            $infos = self::where('upid', '=', 0)->where('type', 1)->select(['id', 'name'])->orderBy('displayorder', 'asc')->get()->toArray();
            return json_encode($infos, JSON_UNESCAPED_UNICODE);
        });
        return json_decode($result, true);
    }


    /**
     * 用于select的城市列表
     * @return array
     */
    public static function getCityList($provinceId)
    {
        $result = \Cache::tags(self::CACHE_TAG)->rememberForever('new-city-list:' . $provinceId, function () use ($provinceId) {
            $infos = self::where('upid', '=', $provinceId)->where('type', 2)->select(['id', 'name'])->get()->toArray();
            return json_encode($infos, JSON_UNESCAPED_UNICODE);
        });
        return json_decode($result, true);

    }

    /**
     * 用于select的地区列表
     * @return array
     */
    public static function getDistrictsList($cityId)
    {
        $result = \Cache::tags(self::CACHE_TAG)->rememberForever('new-district-list:' . $cityId, function () use ($cityId) {
            $infos = self::where('upid', '=', $cityId)->where('type', 3)->select(['id', 'name'])->get()->toArray();
            return json_encode($infos, JSON_UNESCAPED_UNICODE);
        });
        return json_decode($result, true);
    }

    /**
     * 清除缓存
     */
    public function clearCache()
    {
        \Cache::tags(self::CACHE_TAG)->flush();
    }

    //调取省、市名称
    public function getProvinceCityName($id)
    {
        return District::find($id)->name;
    }

    //调取学校名称
    public function getSchoolName($schoolId)
    {
        return School::find($schoolId)->name;
    }
}